package com.yubest.demo.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.yubest.demo.anno.SignProcess;
import com.yubest.demo.dto.DemoReqDTO;
import com.yubest.demo.dto.DemoRespDTO;
import com.yubest.demo.dto.Response;
import com.yubest.demo.util.JsonUtil;
import com.yubest.demo.util.SignUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @Author hweiyu
 * @Description
 * @Date 2021/3/1 14:01
 */
@RestController
public class DemoController {

    /**
     * @param reqDTO
     * @return
     */
    @SignProcess
    @PostMapping(value = "/test")
    public Response<DemoRespDTO> test(@RequestBody DemoReqDTO reqDTO) {
        DemoRespDTO respDTO = new DemoRespDTO();
        respDTO.setA(1);
        respDTO.setB(new DemoRespDTO.BBean().setC("ccc").setD("ddd"));
        respDTO.setE(Arrays.asList("e1", "e2"));
        return Response.success(respDTO);
    }

    public static void main(String[] args) {
        //创建测试使用的json串
        //原始json串
        String rawJsonStr = "{\"k10\":[1,2],\"k3\":{\"k4\":\"v4\",\"k5\":\"v5\"},\"k6\":[{\"k7\":\"v7\",\"k8\":8}],\"k9\":9,\"k2\":\"v2\",\"k1\":\"v1\"}";

        TreeMap<String, String> map = new TreeMap<>();
        Iterator<Map.Entry<String, JsonNode>> fields = JsonUtil.read(rawJsonStr).fields();
        while(fields.hasNext()){
            Map.Entry<String, JsonNode> entry = fields.next();
            map.put(entry.getKey(), JsonUtil.toStr(entry.getValue()));
        }
        SignUtil.sign(map, "1234567890abcdef");
        //原始json串
        System.out.println("原始json串：" + rawJsonStr);
        //测试请求json串，value值为对象或数组的情况，都转换为json串
        System.out.println("实际请求参数：" + JsonUtil.toStr(map));
    }

}
